package com.bishe.tax.service;

import com.bishe.tax.entity.InvoiceApply;
import com.bishe.tax.entity.SysUser;
import com.bishe.tax.entity.Taxpayer;
import com.bishe.tax.mapper.InvoiceApplyMapper;
import com.bishe.tax.utils.Convert;

import org.activiti.engine.IdentityService;
import org.activiti.engine.RuntimeService;
import org.activiti.engine.runtime.ProcessInstance;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 发票申请 服务层实现
 *
 * @author ruoyi
 * @date 2019-06-23
 */
@Service
public class InvoiceApplyService {
	@Autowired
	private InvoiceApplyMapper applyMapper;
	@Autowired
	IdentityService identityservice;
	@Autowired
	RuntimeService runtimeservice;
	@Autowired
	org.activiti.engine.TaskService taskservice;

	/**
	 * 查询发票申请信息
	 *
	 * @param iaId
	 *            发票申请ID
	 * @return 发票申请信息
	 */

	public InvoiceApply selectApplyById(Integer iaId) {
		return applyMapper.selectApplyById(iaId);
	}

	/**
	 * 查询发票申请列表
	 *
	 * @param apply
	 *            发票申请信息
	 * @return 发票申请集合
	 */
	public List<InvoiceApply> selectApplyList(InvoiceApply apply) {
		return applyMapper.selectApplyList(apply);
	}

	/**
	 * 新增发票申请
	 *
	 * @param apply
	 *            发票申请信息
	 * @return 结果
	 */
	public int insertApply(InvoiceApply apply) {
		return applyMapper.insertApply(apply);
	}

	/**
	 * 修改发票申请
	 *
	 * @param apply
	 *            发票申请信息
	 * @return 结果
	 */

	public int updateApply(InvoiceApply apply) {
		return applyMapper.updateApply(apply);
	}

	/**
	 * 删除发票申请对象
	 *
	 * @param ids
	 *            需要删除的数据ID
	 * @return 结果
	 */

	public int deleteApplyByIds(String ids) {
		String []ar =ids.split(",");
		for (String id : ar){
			InvoiceApply ia = applyMapper.selectApplyById(Integer.valueOf(id));
			if (ia != null && StringUtils.isNotBlank(ia.getProcessInstanceId())) {
				runtimeservice.deleteProcessInstance(ia.getProcessInstanceId(),"");
			}
		}
		return applyMapper.deleteApplyByIds(Convert.toStrArray(ids));
	}

	public int doSubmitFlow(SysUser user, String iaId) {
		InvoiceApply apply = applyMapper.selectApplyById(Integer.valueOf(iaId));
		Map<String, Object> variables = new HashMap<>();
		String creator = user.getUserId().toString();
		variables.put("creator", creator);
		variables.put("type", "invoiceApply");
		identityservice.setAuthenticatedUserId(user.getUserId().toString());
		ProcessInstance instance = runtimeservice.startProcessInstanceByKey("singleExamine", apply.getIaId().toString(),
				variables);
		apply.setProcessInstanceId(instance.getId());
		apply.setIaStatus(2);
		return applyMapper.updateApply(apply);
	}
}
